<?php
namespace hema\device\engine;

use hema\Http;

/**
 * 飞鹅打印机驱动引擎
 * 测试机型号：D1,D2
 */
class Mstching extends Basics
{
    /**
     * 构造方法
     */
    public function __construct($dev_type, $device, $data, $tpl)
    {
        parent::__construct($dev_type, $device, $data, $tpl);
    }

    /*
     * 用户设备绑定
     */
    public function add()
    {
        $data = $this->data;
        $url = $this->getUrl("/home/userbind");
        $queryarr = [
            'Uuid' => $data['dev_key'], //设备编号
            'UserId' => $data['dev_key'], //与对对机平台关联的用户唯一标示（你自己系统定义的）
            'DeviceName' => $data['dev_name'] //自定义设备名称
        ];
        $head = $this->http_head($queryarr);
        $result = json_decode(Http::post($url,json_encode($queryarr),[],$head),true);
        if($result['Code']!=200){//绑定不成功
            $this->error = $result['Message'];
            return false;
        } 
        return $result;
    }
    
    /*
     * 获取设备状态                          
     * $uuid 设备编号
     * 返回数据格式：{"State":0,"Code":200,"Message":"成功"}
     * State状态值(-1错误 0正常 1缺纸 2温度保护报警 3忙碌 4离线)
     */
    public function status()
    {
        $url = $this->getUrl("/home/getdevicestate");
        $queryarr = ['Uuid' => $this->data['dev_key']];
        $head = $this->http_head($queryarr);
        $result = json_decode(Http::post($url,json_encode($queryarr),[],$head),true);
        if(isset($result['Code']) AND $result['Code']==200){//查询成功
            return $this->getState($result['State']);
        }
        return '未知';
    }
    
    /*
     * 打印信息
     * $dev 设备参数
     * $order 打印订单数据
     * $tpl 模板类型
     * 返回数据格式：{"TaskId":1,"Code":200,"Message":"成功"}
     * TaskId  打印任务编号
     */
    public function print()
    {
        if($this->tpl==0){
            $content = $this->make_order_templet($this->data,$this->device['dev_model']);//生成订单模板
        }else{
            $content = $this->make_refund_templet($this->data,$this->device['dev_model']);//生成退单模板
        }
        $url = $this->getUrl("/home/printcontent2");
        $queryarr = [
            'Uuid' => $this->device['dev_key'], //设备key
            'PrintContent'=>' '.$content, //打印的内容
            'OpenUserId'=> $this->device['dev_id'] //设备编号
        ];
        $head = $this->http_head($queryarr);
        //打印份数
        for($n=0;$n<$this->device['values']['prt_num'];$n++){
            $result = json_decode(Http::post($url,json_encode($queryarr),[],$head),true);
        }
        return true;
    }
    public function getToken()
    {

    }
    public function edit()
    {
        
    }
    public function push()
    {
        
    }
    public function delete()
    {
        
    }

    /**
     * 生成请求头文件
     */
    private function http_head($data)
    {
        return [
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen(json_encode($data))
        ];
    }
    
    //创建通用请求参数
    private function createParams()
    {
        $nonce = $this->getNonce();
        $timeStamp = $this->getTimestamp();
        $signStr = $this->signatureString($this->config['app_secret'], $timeStamp, $nonce);
        return '?appid='.$this->config['app_key'].'&nonce='.$nonce.'&'.'timestamp='.$timeStamp.'&signature='.$signStr;
    }
    //获取请求url
    private function getUrl($action)
    {
        $params = $this->createParams();
        return $this->config['api_url'] . $action . $params;
    }
    //获取随机数
    private function getNonce()
    {
        return ''.rand(100000000,999999999);
    }
    //获取时间戳
    private function getTimestamp()
    {    
        return ''.intval(time());
    }
    //sha1 加密
    private function signatureString($appSecret,$timestamp,$nonce)
    {    
        $arrTmp = array($appSecret,$timestamp,$nonce);
        asort($arrTmp,SORT_LOCALE_STRING);
        $strTmp = implode('', $arrTmp);
        return strtolower(sha1($strTmp));
    }
    
    //设备状态
    private function getState($value)
    {
        if($value<0 OR $value>4){
            return '错误';
        }
        $state = [
            '0' => '正常',
            '1' => '缺纸',
            '2' => '高温',
            '3' => '忙碌',
            '4' => '离线'
        ];
        return $state[$value];
        
    }
    
    //服务请求错误代码
    private function p_err($code='')
    {
        if(empty($code)){
            return '未知';
        }
        $err = [
            '200' => '成功',
            '1000' => '服务处理异常',
            '1001' => '验证签名错误',
            '1002' => '链接失效',
            '1003' => '参数错误',
            '1004' => 'AppId不存在',
            '1005' => '设备不存在',
            '1006' => '开发者账号已被禁用',
            '1007' => '任务不存在或权限不足',
            '1008' => '未通过认证',
            '1009' => '限制调用',
            '1010' => '设备未连接',
            '1011' => '与服务器断开链接',
            '1012' => '打印任务不能为空'
        ];
        return $err[$code];
    }       

    /**
     * 制作订单模板
     * $data 订单数据
     * $model 打印机型号 
     */
    private function make_order_templet($data,$model=2)
    {
        $content = [];
        $code = 'UTF-8//IGNORE'; //默认D2
        $font_b = 3;
        $font_s = 0;
        $font_m = 11;
        $str = "................................................";
        if($model==1){ //如果是D1机型
            $code = 'GBK//IGNORE';
            $font_b = 1;
            $font_s = 0;
            $font_m = 0;
            $str = "................................";
        }
        if($data['order_mode']['value']==10){
            if(isset($data['table']['table_name'])){
                $title = $data['table']['table_name'];
            }else{
                $title = '堂食'.$data['row_no'].'号';
            }
        }
        if($data['order_mode']['value']==20){
            $title = '外卖'.$data['row_no'].'号';
        }
        if($data['order_mode']['value']==30){
            $title = '自取'.$data['row_no'].'号';
        }
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 1,
            'Bold' => 1,
            'FontSize' => $font_b,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '# ' . $title . ' #'))
        ];
        if($data['arrive_time']['value']>0){
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_s,
                'BaseText' => base64_encode(iconv('UTF-8', $code, '到店时间：' . $data['arrive_time']['text']))
            ];
        }
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_m,
            'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 1,
            'Bold' => 0,
            'FontSize' => $font_s,
            'BaseText' => base64_encode(iconv('UTF-8', $code, $data['shop']['shop_name']))
        ];
        if($data['pay_status']['value'] != 30){
            if($data['transaction_id']){
                $pay_title = '微信支付';
            }else{
                $pay_title = '余额支付';
            }
        }else{
            $pay_title = '后付款';
        }
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 1,
            'Bold' => 0,
            'FontSize' => $font_s,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '-- ' . $pay_title . ' --'))
        ];
        if($data['pay_status']['value'] != 30){
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_s,
                'BaseText' => base64_encode(iconv('UTF-8', $code, '支付时间：' . datetime($data['pay_time'])))
            ];
        }
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_b,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '名称        数量'))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_m,
            'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
        ];

        //循环拼接打印模板
        for ($i = 0; $i < sizeof($data['goods']); $i++) {
            $goods_name = $data['goods'][$i]['goods_name'];//产品名字
            !empty($data['goods'][$i]['goods_attr']) && $goods_name .= "/" . $data['goods'][$i]['goods_attr'];
            //设置名称字符长度
            $lan = mb_strlen($goods_name,'utf-8')*2;//
            for($n=$lan;$n<13;$n++){
                $goods_name .= ' ';
            }
            $total_num = $data['goods'][$i]['total_num'];   //产品数量
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_b,
                'BaseText' => base64_encode(iconv('UTF-8', $code, $goods_name . "×" . $total_num))
            ];
        }
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_m,
            'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_s,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '商品金额：+￥'.$data['total_price']))
        ];

        if($data['express_price']>0){
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_s,
                'BaseText' => base64_encode(iconv('UTF-8', $code, '配送费用：+￥'.$data['express_price']))
            ];
        }
        if($data['pack_price']>0){
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_s,
                'BaseText' => base64_encode(iconv('UTF-8', $code, '餐盒费用：+￥'.$data['pack_price']))
            ];
        }
        if($data['ware_price']>0){
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_s,
                'BaseText' => base64_encode(iconv('UTF-8', $code, '餐具调料：+￥'.$data['ware_price']))
            ];
        }
        if($data['activity_price']>0){
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_s,
                'BaseText' => base64_encode(iconv('UTF-8', $code, '优惠金额：-￥'.$data['activity_price']))
            ];
        }
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_s,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '实付金额：￥'.$data['pay_price']))
        ];
        if($data['flavor']){
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_s,
                'BaseText' => base64_encode(iconv('UTF-8', $code, '口味要求：'.$data['flavor']))
            ];
        }
        if($data['message']){
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_s,
                'BaseText' => base64_encode(iconv('UTF-8', $code, '顾客留言：'.$data['message']))
            ];
        }
        
        if($data['order_mode']['value']==20){
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_s,
                'BaseText' => base64_encode(iconv('UTF-8', $code, '配送地址：'.$data['address']['detail']))
            ];
            $content[] = [
                'PrintType' => 0,
                'Alignment' => 0,
                'Bold' => 0,
                'FontSize' => $font_s,
                'BaseText' => base64_encode(iconv('UTF-8', $code, '接 收 人：'.$data['address']['name'].$data['address']['phone']))
            ];
        }
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 1,
            'Bold' => 1,
            'FontSize' => $font_b,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '# ' . $title . ' # 完'))
        ];
        return json_encode($content);
    }
    
    /**
     * 制作退单模板
     * $data 退单数据
     * $model 打印机型号 
     */
    private function make_refund_templet($data,$model=2)
    {
        $content = [];
        $code = 'UTF-8//IGNORE'; //默认D2
        $font_b = 3;
        $font_s = 13;
        $font_m = 11;
        $str = "................................................";
        if($model==1){ //如果是D1机型
            $code = 'GBK//IGNORE';
            $font_b = 1;
            $font_s = 0;
            $font_m = 0;
            $str = "................................";
        }
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 1,
            'Bold' => 1,
            'FontSize' => $font_b,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '# 退单 #'))
        ]; 
         
        if($data['order_mode']['value']==10){
            if(isset($data['table']['table_name'])){
                $title = $data['table']['table_name'];
            }else{
                $title = '堂食'.$data['row_no'].'号';
            }
        }
        if($data['order_mode']['value']==20){
            $title = '外卖'.$data['row_no'].'号';
        }
        if($data['order_mode']['value']==30){
            $title = '自取'.$data['row_no'].'号';
        }

        $content[] = [
            'PrintType' => 0,
            'Alignment' => 1,
            'Bold' => 1,
            'FontSize' => $font_b,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '- ' . $title))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_m,
            'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 1,
            'Bold' => 0,
            'FontSize' => $font_s,
            'BaseText' => base64_encode(iconv('UTF-8', $code, $data['shop']['shop_name']))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_b,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '名称        数量'))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_m,
            'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
        ];
        //循环拼接打印模板
        for ($i = 0; $i < sizeof($data['goods']); $i++) {
            if($data['goods'][$i]['refund_num']>0){
                $goods_name = $data['goods'][$i]['goods_name'];//产品名字
                !empty($data['goods'][$i]['goods_attr']) && $goods_name .= "/" . $data['goods'][$i]['goods_attr'];
                //设置名称字符长度
                $lan = mb_strlen($goods_name,'utf-8')*2;//
                for($n=$lan;$n<13;$n++){
                    $goods_name .= ' ';
                }
                $refund_num=$data['goods'][$i]['refund_num'];   //产品数量
                $content[] = [
                    'PrintType' => 0,
                    'Alignment' => 0,
                    'Bold' => 0,
                    'FontSize' => $font_b,
                    'BaseText' => base64_encode(iconv('UTF-8', $code, $goods_name . "×" . $refund_num))
                ];
            }
        }
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_m,
            'BaseText' => base64_encode(iconv('UTF-8', $code, $str))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_s,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '付款金额：￥'.$data['pay_price']))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_s,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '退款金额：￥'.$data['refund_price']))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 0,
            'Bold' => 0,
            'FontSize' => $font_s,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '退款理由：'.$data['refund_desc']))
        ];
        $content[] = [
            'PrintType' => 0,
            'Alignment' => 1,
            'Bold' => 1,
            'FontSize' => $font_b,
            'BaseText' => base64_encode(iconv('UTF-8', $code, '# 退单 # 完'))
        ];
        return json_encode($content);
    }      
}
